package org.spider.model;

import lombok.Data;
import org.spider.selector.JsonPathSelector;
import org.spider.selector.Selector;
import org.spider.selector.Selectors;

import java.io.Serializable;

/**
 * 抓取规则
 * @author 15911
 */
@Data
public class ExtractRule implements Serializable {

    private String fieldName;

    private ExpressTypeEnum expressionType;

    private String expressionValue;

    private String expressionParams;

    private boolean multi = false;

    private volatile Selector selector;

    private boolean notNull = false;

    public Selector getSelector() {
        if (selector == null) {
            synchronized (this) {
                if (selector == null) {
                    selector = compileSelector();
                }
            }
        }
        return selector;
    }

    public void setSelector(Selector selector) {
        this.selector = selector;
    }

    private Selector compileSelector() {
        switch (expressionType) {
            case CSS:
                if (expressionParams != null) {
                    return Selectors.$(expressionValue, expressionParams);
                } else {
                    return Selectors.$(expressionValue);
                }
            case REGEX:
                if (expressionParams != null) {
                    return Selectors.regex(expressionValue, Integer.parseInt(expressionParams));
                } else {
                    return Selectors.regex(expressionValue);
                }
            case JSONPATH:
                return new JsonPathSelector(expressionValue);
            default:
                return Selectors.xpath(expressionValue);
        }
    }
}
